<?php
require_once(dirname(__FILE__) . '/../include/config.inc.php');
require_once "WxConfig.php";
session_start();
require_once(dirname(__FILE__) . '/../jssdk.php');
$appId = WxConfig::APPID;
$appSecret = WxConfig::APPSECRET;
$jssdk = new JSSDK($appId, $appSecret);
$signPackage = $jssdk->GetSignPackage();
$g_AccessToken = $jssdk->getAccessToken();

// 引入自动加载文件，确保依赖库能够正确加载
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// 多种方式获取OSS配置
function getOssConfig() {
    // 方式3：直接配置（临时方案）
    return [
        'access_key_id' => 'LTAI5tEEsb7cHLjyU5QFpWW4',
        'access_key_secret' => 'WEvIOp1MYLxX0hwxO7lnDFQhmHanVQ',
        'bucket_name' => 'zmdtc',
        'region' => 'cn-beijing',
        'endpoint' => 'https://oss-cn-beijing.aliyuncs.com'
    ];
}

$ossConfig = getOssConfig();

// 验证配置
if (empty($ossConfig['access_key_id']) || empty($ossConfig['access_key_secret'])) {
    die("OSS配置信息不完整，请检查配置文件或环境变量");
}
//从服务器拉取图片

function getPhotoFromWxService($serverId)
{
    global $g_AccessToken;
    //保存地址
    $imgDir = PHPMYWIND_ROOT;
    //要生成的图片名字
    $filename = "file/wx/".date('Ymd')."/" . date('YmdHis') . rand(1000, 9999) . ".jpg"; //新图片名称
    $newFilePath = $imgDir . $filename;
    $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" . $g_AccessToken . "&media_id=" . $serverId;

    try {
        $file_str = httpGet($url);
        // 检查获取到的数据是否有效
        if (empty($file_str)) {
            throw new Exception("从微信服务器获取的图片数据为空");
        }
    } catch (Exception $e) {
        $error_log = dirname(__FILE__)."/txt/".time()."-http-error.txt";
        file_put_contents($error_log, "HTTP获取失败: " . $e->getMessage());
        return false;
    }
    //文件流转图片
//    $newFile = fopen($newFilePath, "w");  //打开文件准备写入
//    fwrite($newFile, $file_str);  //写入二进制流到文件
//    fclose($newFile);  //关闭文件

    // 获取OSS配置
    $ossConfig = getOssConfig();

    // 使用StaticCredentialsProvider直接设置凭证
    $credentialsProvider = new Oss\Credentials\StaticCredentialsProvider(
        $ossConfig['access_key_id'],
        $ossConfig['access_key_secret']
    );

    # 创建配置对象
    $cfg = new Oss\Config();
    $cfg->setCredentialsProvider($credentialsProvider);
    // 设置Region和Endpoint
    $cfg->setRegion($ossConfig['region']);
    $cfg->setEndpoint($ossConfig['endpoint']);
    // 设置其他必要参数
    $cfg->setConnectTimeout(10);

// 创建OSS客户端实例
    $client = new Oss\Client($cfg);
// 创建PutObjectRequest对象，用于上传对象（使用构造函数参数）
    $request = new Oss\Models\PutObjectRequest($ossConfig['bucket_name'], $filename);
    $request->body = Oss\Utils::streamFor($file_str);

// 执行上传操作
    try {

        $result = $client->putObject($request);
        if ($result->statusCode=='200'){
            return "https://{$ossConfig['bucket_name']}.oss-{$ossConfig['region']}.aliyuncs.com/".$filename;
        } else {
            // 记录错误信息
            $error_log = dirname(__FILE__)."/txt/".time()."-error.txt";
            $error_info = [
                'error_type' => 'upload_failed',
                'status_code' => $result->statusCode,
                'filename' => $filename,
                'bucket' => $ossConfig['bucket_name']
            ];
            file_put_contents($error_log, json_encode($error_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
            return false;
        }
    } catch (Exception $e) {
        // 记录详细错误信息
        $error_log = dirname(__FILE__)."/txt/".time()."-error.txt";
        $error_info = [
            'error_type' => 'exception',
            'error_message' => $e->getMessage(),
            'error_code' => $e->getCode(),
            'error_class' => get_class($e),
            'filename' => $filename,
            'config' => [
                'access_key_id' => substr($ossConfig['access_key_id'], 0, 8) . '...', // 只显示前8位
                'region' => $ossConfig['region'],
                'bucket' => $ossConfig['bucket_name'],
                'endpoint' => $ossConfig['endpoint']
            ]
        ];
        file_put_contents($error_log, json_encode($error_info, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        return false;
    }


}


function httpGet($url)
{
    $curl = curl_init();

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_URL, $url);

    // 重要：设置二进制传输模式，确保图片数据不被损坏
    curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

    // 设置用户代理
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');

    // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用
    // 但在Windows环境下可能需要禁用SSL验证
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    $res = curl_exec($curl);

    // 检查是否有错误
    if (curl_error($curl)) {
        $error = curl_error($curl);
        curl_close($curl);
        throw new Exception("HTTP请求失败: " . $error);
    }

    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    if ($httpCode !== 200) {
        curl_close($curl);
        throw new Exception("HTTP请求返回错误状态码: " . $httpCode);
    }

    curl_close($curl);
    return $res;
}


$serverId = htmlspecialchars($_POST['serverId']);

$filename = getPhotoFromWxService($serverId);

$json_data = array('msg' => 'ok');

$errno = array('errno' => 0);

$file_array = array('filename' => $filename);

$json_json = array_merge($errno, $json_data, $file_array);

$data = json_encode($json_json);

echo $data;


?>
